<?php
namespace App\HttpController\Pudu;

use App\Common\Controller\Rest;
use think\Cache;
use think\Db;

class Members extends Rest
{
    public $modelName = 'Member'; // model 类名称

    public function GETIndex()
    {
        $Member = $this->model();
        if ($this->role == 0) {
            // DONE 这个权限能做所有事  清除掉 userId
            unset($this->param['userId']);
        } else {

            // 检查当前登录用户身份 并生成相应的搜索限制条件
            $roleId = $Member->where(['id' => $this->param['userId']])->value('roleId');
            // DONE 推荐账户列表
            if (isset($this->param['refer'])) { // 表示本次请求是本账户推荐的账户列表
                $this->param['referId'] = $this->param['userId'];
            } else {
                switch ($roleId) {
                    case 1:
                        break;
                    case 2:
                        $this->param['shopId'] = $this->param['userId']; // 只能查看本店铺所属的会员
                        break;
                    case 3:
                        // DONE 市代理  可查看下属店铺 和  下属区县
                        $this->param['cityId'] = $this->param['userId'];
                        break;
                    case 5:
                        // DONE 市代理  可查看下属店铺 和  下属区县
                        $this->param['regionId'] = $this->param['userId'];
                        break;
                    default:
                        // DONE 其他权限不做限制
                        $this->error(['msg' => '权限错误!']);
                        break;
                }
            }

        }

        if (isset($this->param['Id'])) {
            // 获取个人信息 用户的比较特殊
            $id = $this->param['userId'];
            $res = $Member->getDataById($id);
            $this->abort($res, ['msg' => '用户不存在!']);
            $memberNum = 0;
            $regionNum = 0;
            $shopNum = 0;
            switch ($this->role) {
                case 3:
                    // DONE 获取下属区域数量
                    $regionNum = $Member->where(['cityId' => $id, 'roleId' => 5])->count();
                    // DONE 获取下属店铺数量
                    $shopNum = $Member->where(['cityId' => $id, 'roleId' => 2])->count();
                    // DONE 获取下属会员数量
                    $memberNum = $Member->where(['cityId' => $id, 'roleId' => 1])->count();
                    break;
                case 5:
                    // DONE 获取下属店铺数量
                    $shopNum = $Member->where(['regionId' => $id, 'roleId' => 2])->count();
                    // DONE 获取下属会员数量
                    $memberNum = $Member->where(['regionId' => $id, 'roleId' => 1])->count();
                case 2:
                    // DONE 获取下属会员数量
                    $memberNum = $Member->where(['shopId' => $id, 'roleId' => 1])->count();
                    break;
            }

            $res['regionNum'] = $regionNum;
            $res['shopNum'] = $shopNum;
            $res['memberNum'] = $memberNum;
            //查询用户的体检信息
            $data = DB::table('admin_userinfo')->where('uid',$this->param['Id'])->find();
            $res['sex'] = $data['sex'];
            $res['height'] = $data['height'];
            $res['weight'] =$data['weight'];
            $res['waist'] =$data['waist'];
            $res['birthday'] = $data['birthday'];
            $res['blood'] = $data['blood'];
            $res['sugar'] = $data['sugar'];
            $res['depart'] = $data['depart'];
            $res['company'] = $data['company'];
            $res['address'] = $data['address'];
            $res['reson'] = $data['reson'];
        } else {
            $res = $Member->getDataList($this->param);
        }
        $this->result($res, ['msg' => self::$model->getError(), 'data' => $res]);
    }

    public function POSTIndex()
    {
        //$this->json(['data' =>$this->param]);

        $model = $this->model();
        $insertData = $this->param;
        $record = [];
        $configs = $this->Configs();
        $RESERVE_CITY = $configs['RESERVE_CITY'];
        $RESERVE_REGION = $configs['RESERVE_REGION'];
        $RESERVE_REFER = $configs['RESERVE_REFER'];
        $RESERVE_REFER_SHOP = $configs['RESERVE_REFER_SHOP'];

        // DONE 检测推荐人姓名 获取推荐人id
        if (!empty($this->param['referUsername'])) {
            $insertData += $this->getReferInfo($this->param['referUsername'], $model);
        }

        // DONE 检测是否存在所属区
        if (!empty($this->param['regionId'])) {
            $insertData += $this->getRegionInfo($this->param['regionId'], $model);
        }

        // DONE 检测是否存在所属省
        if (!empty($this->param['provinceId'])) {
            $insertData += $this->getProvinceInfo($this->param['provinceId'], $model);
        }

        // DONE 检测是否存在所属市
        if (!empty($this->param['cityId'])) {
            $insertData += $this->getCityInfo($this->param['cityId'], $model);
        }

        // DONE 检测是否存在所属店铺
        if (!empty($this->param['shopId'])) {
            $insertData += $this->getshopInfo($this->param['shopId'], $model);
        }

        // DONE 密码加密 / 不提供密码则使用默认密码
        $insertData['password'] = user_md5('000000');
        $insertData['paypass'] = user_md5('123456');

        switch ($this->param['roleId']){
            case 1:
                if ($this->role != 0) {
                    $this->abort(!empty($this->param['productId']), ['msg' => '请选择注册商品']);
                    $productInfo = Db::table('pudu_product')->where('id', $this->param['productId'])->find(); // 默认id为1的商品
                }

                $this->abort($this->role != 2 or $this->role != 0, ['msg' => '总部后台和店铺才能添加会员!']);
                // DONE 获取店铺的所属信息 并继承到会员上

                // 店铺
                if ($this->role == 2) {
                    $shopInfo = $model->where(['id' => $this->param['userId']])->find();
                    // 区县
                    $insertData['regionId'] = $shopInfo['regionId'];
                    $insertData['regionUsername'] = $shopInfo['regionUsername'];
                    $insertData['regionCellphone'] = $shopInfo['regionCellphone'];

                    // 省
                    $insertData['provinceId'] = $shopInfo['provinceId'];
                    $insertData['provinceUsername'] = $shopInfo['provinceUsername'];
                    $insertData['provinceCellphone'] = $shopInfo['provinceCellphone'];

                    // 市
                    $insertData['cityId'] = $shopInfo['cityId'];
                    $insertData['cityUsername'] = $shopInfo['cityUsername'];
                    $insertData['cityCellphone'] = $shopInfo['cityCellphone'];

                    $insertData['shopId'] = $shopInfo['id'];
                    $insertData['shopUsername'] = $shopInfo['username'];
                    $insertData['shopCellphone'] = $shopInfo['cellphone'];
                    // 注册洗肠次数
                    $insertData['washTimes'] = $productInfo['washTimes'];

                    // 检查店铺支付密码是否正确
                    $this->abort(user_md5($this->param['paypass']) == $model->where(['id' => $this->param['userId']])->value('paypass'), ['msg' => '支付密码错误!']);
                }

                // DONE 后台直接添加的用户不参与返现
                if ($this->role == 0) {
                    try {
                        if (!empty($this->param['shopUsername'])) {
                            $shopInfo = $model->where(['username' => $this->param['shopUsername'], 'roleId' => 2])->find();
                            if (!$shopInfo) {
                                throw new \Exception('该店铺不存在');
                            }
                        }
                        if (isset($shopInfo) and $shopInfo) {
                            // 区县
                            $insertData['regionId'] = $shopInfo['regionId'];
                            $insertData['regionUsername'] = $shopInfo['regionUsername'];
                            $insertData['regionCellphone'] = $shopInfo['regionCellphone'];
                            // 省
                            $insertData['provinceId'] = $shopInfo['provinceId'];
                            $insertData['provinceUsername'] = $shopInfo['provinceUsername'];
                            $insertData['provinceCellphone'] = $shopInfo['provinceCellphone'];
                            // 市
                            $insertData['cityId'] = $shopInfo['cityId'];
                            $insertData['cityUsername'] = $shopInfo['cityUsername'];
                            $insertData['cityCellphone'] = $shopInfo['cityCellphone'];
                            $insertData['shopId'] = $shopInfo['id'];
                            $insertData['shopUsername'] = $shopInfo['username'];
                            $insertData['shopCellphone'] = $shopInfo['cellphone'];
                        }

                        $res = $model->createData($insertData);
                        if (!$res) {
                            throw new \Exception($model->getError());
                        }
                        $id = $model->id;

                        // 建立可登录账户
                        $loginInfoData = [
                            'username' => $this->param['username'],
                            'password' => $insertData['password'],
                            'role' => $this->param['roleId'],
                            'userId' => $id,
                        ];
                        Db::table('admin_user')->insert($loginInfoData);
                    } catch (\Exception $e) {
                        $this->error(['msg' => $e->getMessage()]);
                    }

                    $this->result();
                }
                break;
        }

        $MemberRecord = $this->model('MemberRecord');
        $model->startTrans();
        try {
            switch ($this->param['roleId']) {
                case 3:
                    $insertData['level'] = 3;
                    $insertData['referShopNum'] = 50;
                    break;
                case 5:
                    $insertData['level'] = 2;
                    $insertData['referShopNum'] = 10;
                    break;
            }

            // TODO 如果是新增会员 这些不生效
            if ($this->param['roleId'] != 1) {
                // DONE 通过地址信息获取所属市代理
                $cityInfo = $model->where(['roleId' => 3, 'province' => $insertData['province'], 'city' => $insertData['city']])->find();
                if ($cityInfo) { // 如果所属地区有市代 那么绑定这个市代 (没有就不绑定 这个区县就没有所属市  后期市填上之后再自动匹配上所属市)
                    // 获取插入区县的市代信息
                    $insertData['cityId'] = $cityInfo['id'];
                    $insertData['cityUsername'] = $cityInfo['username'];
                    $insertData['cityCellphone'] = $cityInfo['cellphone'];
                }

                // DONE 通过地址信息获取所属区县代理
                $regionInfo = $model->where(['roleId' => 5, 'province' => $insertData['province'], 'city' => $insertData['city'], 'hometown' => $insertData['hometown']])->find();
                if ($regionInfo) { // 如果所属地区有市代 那么绑定这个市代 (没有就不绑定 这个区县就没有所属市  后期市填上之后再自动匹配上所属市)
                    $insertData['regionId'] = $regionInfo['id'];
                    $insertData['regionUsername'] = $regionInfo['username'];
                    $insertData['regionCellphone'] = $regionInfo['cellphone'];
                }
            }

            $res = $model->createData($insertData);
            if (!$res) {
                throw new \Exception($model->getError());
            }
            $id = $model->id;

            // 建立可登录账户
            $loginInfoData = [
                'username' => $this->param['username'],
                'password' => $insertData['password'],
                'role' => $this->param['roleId'],
                'userId' => $id,
            ];
            Db::table('admin_user')->insert($loginInfoData);

            //如果有体检的相关信息 存储到数据库
            $data = $this->userInfo($this->param);
            if(!empty($data)){
                $data['uid'] = $id;
                $data['addtime'] = date('Y-m-d H:i:s');
                Db::table('admin_userinfo')->insert($data);
            }
            

            switch ($this->param['roleId']) {
                case 1:
                    // 新增普通用户
                    $this->abort($productInfo, ['msg' => '注册商品信息有误!']);
                    $price = $productInfo['productPrice'];

                    // DONE 扣除店铺对应的电子币 并生成记录
                    $emoney = $model->where(['id' => $insertData['shopId']])->value('emoney');
                    if ($emoney < $price) {
                        throw new \Exception('电子币余额不足');
                    }                

                    $model->where(['id' => $insertData['shopId']])->setDec('emoney', $price);
                    $record[] = [
                        'userId' => $insertData['shopId'],
                        'username' => $insertData['shopUsername'],
                        'change' => -$price,
                        'remain' => $emoney - $price,
                        'type' => 3,
                        'remark' => '注册会员',
                    ];

                    // DONE 给用户加上相应积分
                    $point = $model->where(['id' => $id])->value('point');
                    $model->where(['id' => $id])->setInc('point', $productInfo['returnPoint']);

                    $record[] = [
                        'userId' => $id,
                        'username' => $this->param['username'],
                        'change' => $price,
                        'remain' => $point + $productInfo['returnPoint'],
                        'type' => 2,
                        'remark' => '会员注册',
                    ];

                    // DONE 给用户增加响应的洗肠次数 并生成记录
                    $WashRecord = [
                        'userId' => $id,
                        'shopId' => $this->param['userId'],
                        'shopUsername' => $insertData['shopUsername'],
                        'washUsername' => $insertData['username'],
                        'artificer' => '',
                        'washTimes' => $productInfo['washTimes'],
                        'remark' => '会员注册',
                    ];

                    $this->model('WashRecord')->insert($WashRecord);

                    // DONE 为该用户不同的上级发放相应的返现金额  并生成记录
                    //1 存在推荐人的情况下
                    if (isset($insertData['referId'])) {
                        //推荐人得利
                        $referPrice = $productInfo['referReserve'];
                        //推荐人所属店铺得利
                        $pshopReserve = $productInfo['pshopReserve'];
                        //店铺推荐人得利
                        $personPrice = $productInfo['personReserve'];
                        $balance = $model->where(['id' => $insertData['referId']])->value('balance');
                        $model->where(['id' => $insertData['referId']])->setInc('balance', $referPrice);

                        $record[] = [
                            'userId' => $insertData['referId'],
                            'username' => $insertData['referUsername'],
                            'change' => $referPrice,
                            'remain' => $balance + $referPrice,
                            'type' => 1,
                            'remark' => '推荐会员',
                        ];
                        //推荐人所属店铺
                        $shopid = DB::table('pudu_members')->where('id',$insertData['referId'])->value('shopId');
                        if($shopid){
                            $shop_balance = $model->where(['id' => $shopid])->value('balance');
                            $model->where(['id' => $shopid])->setInc('balance', $pshopReserve);
                            $record[] = [
                                'userId' => $shopid,
                                'username' => $insertData['referUsername'],
                                'change' => $pshopReserve,
                                'remain' => $shop_balance + $pshopReserve,
                                'type' => 1,
                                'remark' => '推荐会员',
                            ];

                        }
                    }

                    //2 店铺
                    $referPrice = $productInfo['shopReserve'];
                    $balance = $model->where(['id' => $insertData['shopId']])->value('balance');
                    $model->where(['id' => $insertData['shopId']])->setInc('balance', $referPrice);

                    $record[] = [
                        'userId' => $insertData['shopId'],
                        'username' => $insertData['shopUsername'],
                        'change' => $referPrice,
                        'remain' => $balance + $referPrice,
                        'type' => 1,
                        'remark' => '推荐会员',
                    ];
                    //查询是否有店铺推荐人
                    $personid =  $model->where(['id' => $insertData['shopId']])->value('referId');
                    if($personid){
                        $person_balance = $model->where(['id' => $personid])->value('balance');
                        $model->where(['id' => $personid])->setInc('balance', $person_balance);
                        //生成记录
                        $record[] = [
                            'userId' => $personid,
                            'username' => $insertData['shopUsername'],
                            'change' => $personPrice,
                            'remain' => $person_balance + $personPrice,
                            'type' => 1,
                            'remark' => '推荐会员',
                        ];
                    }
                    //3 存在区县代  区县代理取消
                    /*if ($insertData['regionId']) {
                        $referPrice = $productInfo['regionReserve'];
                        $balance = $model->where(['id' => $insertData['regionId']])->value('balance');
                        $model->where(['id' => $insertData['regionId']])->setInc('balance', $referPrice);

                        $record[] = [
                            'userId' => $insertData['regionId'],
                            'username' => $insertData['regionUsername'],
                            'change' => $referPrice,
                            'remain' => $balance + $referPrice,
                            'type' => 1,
                            'remark' => '推荐会员',
                        ];
                    }
*/
                    //4 存在市代
                    if ($insertData['cityId']) {
                        $referPrice = $productInfo['cityReserve'];
                        $balance = $model->where(['id' => $insertData['cityId']])->value('balance');
                        $model->where(['id' => $insertData['cityId']])->setInc('balance', $referPrice);

                        $record[] = [
                            'userId' => $insertData['cityId'],
                            'username' => $insertData['cityUsername'],
                            'change' => $referPrice,
                            'remain' => $balance + $referPrice,
                            'type' => 1,
                            'remark' => '推荐会员',
                        ];
                    }

                    // DONE 为会员生成订单信息
                    $orderData = [
                        'productId' => 1,
                        'shopId' => $insertData['shopId'],
                        'userId' => $id,
                        'productName' => $productInfo['productName'],
                        'totalPrice' => $productInfo['productPrice'] * 1, // 默认购买一份
                        'username' => $insertData['username'],
                        'productNum' => 1,
                        'type' => 2, // 电子币消费
                        'shopName' => $insertData['shopUsername'],
                    ];
                    Db::table('pudu_orders')->insert($orderData);
                    break;
                case 2:
                    // 新增店铺代理
                    $joinPrice = $insertData['joinMoney'];
                    $referPrice = $joinPrice * $RESERVE_REFER / 100;
                    // DONE 检查是否存在推荐人
                    if (isset($insertData['referId'])) {
                        $balance = $model->where(['id' => $insertData['referId']])->value('balance');
                        $model->where(['id' => $insertData['referId']])->setInc('balance', $referPrice);

                        $record[] = [
                            'userId' => $insertData['referId'],
                            'username' => $insertData['referUsername'],
                            'change' => $referPrice,
                            'remain' => $balance + $referPrice,
                            'type' => 1,
                            'remark' => '推荐店铺',
                        ];

                        // DONE 检查推荐人所属店铺
                        $referUserInfo = $model->where(['id' => $insertData['referId']])->find();
                        if ($referUserInfo['roleId'] == 1) {
                            $referPrice = $joinPrice * $RESERVE_REFER_SHOP / 100;
                            $balance = $model->where(['id' => $referUserInfo['shopId']])->value('balance');
                            $model->where(['id' => $referUserInfo['shopId']])->setInc('balance', $referPrice);
                            $record[] = [
                                'userId' => $referUserInfo['shopId'],
                                'username' => $referUserInfo['shopUsername'],
                                'change' => $referPrice,
                                'remain' => $balance + $referPrice,
                                'type' => 1,
                                'remark' => '下属会员推荐区县代理',
                            ];
                        }

                        // TODO 检查推荐人董事界别是否正确
                        $this->referShopNumPlus($referUserInfo, 1, $model);
                    }
                    // DONE 获取所属市代理
                    if ($cityInfo) { // 如果所属地区有市代 那么绑定这个市代 (没有就不绑定 这个店铺就没有所属市  后期市填上之后再自动匹配上所属市)

                        $referPrice = $joinPrice * $RESERVE_CITY / 100;
                        $balance = $model->where(['id' => $cityInfo['id']])->value('balance');
                        $model->where(['id' => $cityInfo['id']])->setInc('balance', $referPrice);

                        $record[] = [
                            'userId' => $cityInfo['id'],
                            'username' => $cityInfo['username'],
                            'change' => $referPrice,
                            'remain' => $balance + $referPrice,
                            'type' => 1,
                            'remark' => '新增下属店铺',
                        ];
                    }

                    // DONE 获取所属区县代理
                    if ($regionInfo) { // 如果所属地区有市代 那么绑定这个市代 (没有就不绑定 这个店铺就没有所属市  后期市填上之后再自动匹配上所属市)

                        $referPrice = $joinPrice * $RESERVE_REGION / 100;
                        $balance = $model->where(['id' => $regionInfo['id']])->value('balance');
                        $model->where(['id' => $regionInfo['id']])->setInc('balance', $referPrice);

                        $record[] = [
                            'userId' => $regionInfo['id'],
                            'username' => $regionInfo['username'],
                            'change' => $referPrice,
                            'remain' => $balance + $referPrice,
                            'type' => 1,
                            'remark' => '新增下属店铺',
                        ];
                    }
                    break;
                case 3:
                    // DONE 检查该市是否已经存在代理
                    $res = $model->where(['roleId' => 3, 'province' => $insertData['province'], 'city' => $insertData['city']])->count();
                    if ($res > 1) {
                        throw new \Exception('该地区已有市代理');
                    }

                    // DONE 检查是否该市下属区县代
                    $cityData = [
                        'cityUsername' => $insertData['username'],
                        'cityId' => $id,
                        'cityCellphone' => $insertData['cellphone'],
                    ];
                    // 更新所有所辖区县代
                    $model->where(['province' => $insertData['province'], 'city' => $insertData['city']])->where('roleId', 'in', '1,2,5')->update($cityData);

                    $joinPrice = $insertData['joinMoney'];
                    $referPrice = $joinPrice * $RESERVE_REFER / 100;
                    // DONE 检查是否存在推荐人
                    if (isset($insertData['referId'])) {
                        $balance = $model->where(['id' => $insertData['referId']])->value('balance');
                        $model->where(['id' => $insertData['referId']])->setInc('balance', $referPrice);

                        $record[] = [
                            'userId' => $insertData['referId'],
                            'username' => $insertData['referUsername'],
                            'change' => $referPrice,
                            'remain' => $balance + $referPrice,
                            'type' => 1,
                            'remark' => '推荐市代理',
                        ];

                        // DONE 检查推荐人所属店铺
                        $referUserInfo = $model->where(['id' => $insertData['referId']])->find();
                        if ($referUserInfo['roleId'] == 1) {
                            $referPrice = $joinPrice * $RESERVE_REFER_SHOP / 100;
                            $balance = $model->where(['id' => $referUserInfo['shopId']])->value('balance');
                            $model->where(['id' => $referUserInfo['shopId']])->setInc('balance', $referPrice);
                            $record[] = [
                                'userId' => $referUserInfo['shopId'],
                                'username' => $referUserInfo['shopUsername'],
                                'change' => $referPrice,
                                'remain' => $balance + $referPrice,
                                'type' => 1,
                                'remark' => '下属会员推荐区县代理',
                            ];
                        }

                        // TODO 推荐人董事级别检查
                        $cityToRegion = 5;
                        $regionToShop = 5;
                        $referNumber = 1 * $cityToRegion * $regionToShop;
                        $this->referShopNumPlus($referUserInfo, $referNumber, $model);
                    }
                    break;
                case 4:

                    break;
                case 5:
                    // DONE 检查区县代是否已经存在
                    $res = $model->where(['roleId' => 5, 'province' => $insertData['province'], 'city' => $insertData['city'], 'hometown' => $insertData['hometown']])->count();
                    if ($res > 1) {
                        throw new \Exception('该地区已有区县代理');
                    }

                    // 更新所有下属 店铺和会员
                    $regionData = [
                        'regionUsername' => $insertData['username'],
                        'regionId' => $id,
                        'regionCellphone' => $insertData['cellphone'],
                    ];
                    $model->where(['province' => $insertData['province'], 'city' => $insertData['city'], 'hometown' => $insertData['hometown']])->where('roleId', 'in', '1,2')->update($regionData);

                    $joinPrice = $insertData['joinMoney'];
                    $referPrice = $joinPrice * $RESERVE_REFER / 100;
                    // DONE 检查是否存在推荐人
                    if (isset($insertData['referId'])) {
                        $balance = $model->where(['id' => $insertData['referId']])->value('balance');
                        $model->where(['id' => $insertData['referId']])->setInc('balance', $referPrice);

                        $record[] = [
                            'userId' => $insertData['referId'],
                            'username' => $insertData['referUsername'],
                            'change' => $referPrice,
                            'remain' => $balance + $referPrice,
                            'type' => 1,
                            'remark' => '推荐区县代理',
                        ];

                        // DONE 检查推荐人所属店铺
                        $referUserInfo = $model->where(['id' => $insertData['referId']])->find();
                        if ($referUserInfo['roleId'] == 1) {
                            $referPrice = $joinPrice * $RESERVE_REFER_SHOP / 100;
                            $balance = $model->where(['id' => $referUserInfo['shopId']])->value('balance');
                            $model->where(['id' => $referUserInfo['shopId']])->setInc('balance', $referPrice);
                            $record[] = [
                                'userId' => $referUserInfo['shopId'],
                                'username' => $referUserInfo['shopUsername'],
                                'change' => $referPrice,
                                'remain' => $balance + $referPrice,
                                'type' => 1,
                                'remark' => '下属会员推荐区县代理',
                            ];
                        }

                        // TODO 推荐人董事级别检查
                        $regionToShop = 5;
                        $referNumber = 1 * $regionToShop;
                        $this->referShopNumPlus($referUserInfo, $referNumber, $model);
                    }

                    // DONE 通过地址信息获取所属市代理
                    $cityInfo = $model->where(['roleId' => 3, 'province' => $insertData['province'], 'city' => $insertData['city']])->find();
                    if ($cityInfo) { // 如果所属地区有市代 那么绑定这个市代 (没有就不绑定 这个区县就没有所属市  后期市填上之后再自动匹配上所属市)

                        $referPrice = $joinPrice * $RESERVE_CITY / 100;
                        $balance = $model->where(['id' => $cityInfo['id']])->value('balance');
                        $model->where(['id' => $cityInfo['id']])->setInc('balance', $referPrice);

                        $record[] = [
                            'userId' => $cityInfo['id'],
                            'username' => $cityInfo['username'],
                            'change' => $referPrice,
                            'remain' => $balance + $referPrice,
                            'type' => 1,
                            'remark' => '新增下属区县代理',
                        ];
                    }

                    break;
            }
            if (count($record)) { // 防止出现没有任何记录要插入的情况
                $MemberRecord->insertAll($record);
            }
            $model->commit();
        } catch (\Exception $e) {
            $model->rollback();
            $this->error(['msg' => $e->getMessage()]);

        }

        $this->result($res, ['msg' => $model->getError()]);
    }

    /**
     * 修改用户信息
     *
     * @return void
     */
    public function PUTIndex()
    {
        // DONE 判断是否涉及到 现金余额 / 电子币 / 积分
        $Member = $this->model();
        if ($this->role != 0) {
            $this->param['Id'] = $this->param['userId'];
        }
        echo $this->param['Id'];
        $userInfo = $Member->get($this->param['Id']);
        //$this->json(['data'=>$userInfo]);
        // DONE 参数存在并且和之前的数据不一致
        $record = [];
        $remark = isset($this->param['remark']) ? $this->param['remark'] : '';
        if (isset($this->param['balance']) && $userInfo['balance'] != $this->param['balance']) {
            // DONE 减少金额
            $record[] = [
                'userId' => $this->param['Id'],
                'username' => $userInfo['username'],
                'change' => $this->param['balance'] - $userInfo['balance'],
                'remain' => $this->param['balance'],
                'type' => 1,
                'remark' => $remark,
            ];
        }
        if (isset($this->param['point']) && $userInfo['point'] != $this->param['point']) {
            $record[] = [
                'userId' => $this->param['Id'],
                'username' => $userInfo['username'],
                'change' => $this->param['point'] - $userInfo['point'],
                'remain' => $this->param['point'],
                'type' => 2,
                'remark' => $remark,
            ];
        }
        if (isset($this->param['emoney']) && $userInfo['emoney'] != $this->param['emoney']) {
            $record[] = [
                'userId' => $this->param['Id'],
                'username' => $userInfo['username'],
                'change' => $this->param['emoney'] - $userInfo['emoney'],
                'remain' => $this->param['emoney'],
                'type' => 3,
                'remark' => $remark,
            ];
        }
        if (isset($this->param['share']) && $userInfo['share'] != $this->param['share']) {
            $record[] = [
                'userId' => $this->param['Id'],
                'username' => $userInfo['username'],
                'change' => $this->param['share'] - $userInfo['share'],
                'remain' => $this->param['share'],
                'type' => 4,
                'remark' => $remark,
            ];
        }

        if (isset($this->param['referUsername']) && $userInfo['referUsername'] != $this->param['referUsername']) {
            // DONE 通过账户名 查询推荐人id

            $referInfo = $Member->where(['username' => $this->param['referUsername']])->find();
            $this->abort($referInfo, ['msg' => '推荐人不存在!']);
            $this->param['referId'] = $referInfo['id'];
            $this->param['referCellphone'] = $referInfo['cellphone'];
        }

        // DONE 支付密码
        if (!empty($this->param['paypassForModify']) && $userInfo['paypass'] != $this->param['paypassForModify']) {
            $this->param['paypass'] = user_md5($this->param['paypassForModify']);
        }

        // 修改董事级别
        if (isset($this->param['level']) && $userInfo['level'] != $this->param['level']) {
            $level = $this->param['level'];
            // TODO 更新董事级别
            $configs = $this->Configs();
            $limit1 = $configs['LEVEL_NUM_1'];
            $limit2 = $configs['LEVEL_NUM_2'];
            $limit3 = $configs['LEVEL_NUM_3'];
            $limit4 = $configs['LEVEL_NUM_4'];
            $limit5 = $configs['LEVEL_NUM_5'];
            $limit6 = $configs['LEVEL_NUM_6'];
            $limit7 = $configs['LEVEL_NUM_7'];
            $limitName = 'limit'.$level;
            $this->param['referShopNum'] = $limitName;
        }


        $Member->startTrans();

        if (isset($this->param['referShopNum']) && $userInfo['referShopNum'] != $this->param['referShopNum']) {
            $referShopNum = $this->param['referShopNum'];
            // TODO 更新董事级别
            $configs = $this->Configs();
            $limit1 = $configs['LEVEL_NUM_1'];
            $limit2 = $configs['LEVEL_NUM_2'];
            $limit3 = $configs['LEVEL_NUM_3'];
            $limit4 = $configs['LEVEL_NUM_4'];
            $limit5 = $configs['LEVEL_NUM_5'];
            $limit6 = $configs['LEVEL_NUM_6'];
            $limit7 = $configs['LEVEL_NUM_7'];

            if ($referShopNum >= $limit1 and $referShopNum < $limit2) { // 2-10 一级董事
                $this->param['level'] = 1;
            }

            if ($referShopNum >= $limit2 and $referShopNum < $limit3) { // 2-10 一级董事
                $this->param['level'] = 2;
            }

            if ($referShopNum >= $limit3 and $referShopNum < $limit4) { // 2-10 一级董事
                $this->param['level'] = 3;
            }

            if ($referShopNum >= $limit4 and $referShopNum < $limit5) { // 2-10 一级董事
                $this->param['level'] = 4;
            }

            if ($referShopNum >= $limit5 and $referShopNum < $limit6) { // 2-10 一级董事
                $this->param['level'] = 5;
            }

            if ($referShopNum >= $limit6 and $referShopNum < $limit7) { // 2-10 一级董事
                $this->param['level'] = 6;
            }

            if ($referShopNum >= $limit7) { // 2-10 一级董事
                $this->param['level'] = 7;
            }

        }

        try {
            // DONE 密码
            if (!empty($this->param['password'])){
                // DONE 通过账户名 查询推荐人id
                Db::table('admin_user')->where(['username' => $userInfo['username']])->update(['password' => user_md5($this->param['password'])]);
            }

            // DONE 所属市代
            if (!empty($this->param['cityId']) && $userInfo['cityId'] != $this->param['cityId']) {
                $cityInfo = $Member->where(['id' => $this->param['cityId']])->find();
                $this->abort($cityInfo, ['msg' => '市代不存在!']);
                $this->param['cityCellphone'] = $cityInfo['cellphone'];
                $this->param['cityUsername'] = $cityInfo['username'];
            }

            // DONE 所属区县
            if (!empty($this->param['regionId']) && $userInfo['regionId'] != $this->param['regionId']) {
                $regionInfo = $Member->where(['id' => $this->param['regionId']])->find();
                $this->abort($regionInfo, ['msg' => '区县不存在!']);
                $this->param['regionCellphone'] = $regionInfo['cellphone'];
                $this->param['regionUsername'] = $regionInfo['username'];
            }

            // DONE 所属店铺
            if (!empty($this->param['shopId']) && $userInfo['shopId'] != $this->param['shopId']) {
                $shopInfo = $Member->where(['id' => $this->param['shopId'], 'roleId' => 2])->find();
                $this->abort($shopInfo, ['msg' => '店铺不存在!']);
                $this->param['shopCellphone'] = $shopInfo['cellphone'];
                $this->param['shopUsername'] = $shopInfo['username'];
            }

            // DONE 所属店铺(通过店铺名称修改)
            if (!empty($this->param['shopUsername']) && $userInfo['shopUsername'] != $this->param['shopUsername']) {
                $shopInfo = $Member->where(['username' => $this->param['shopUsername'], 'roleId' => 2])->find();
                $this->abort($shopInfo, ['msg' => '店铺不存在!']);
                $this->param['shopCellphone'] = $shopInfo['cellphone'];
                $this->param['shopId'] = $shopInfo['id'];
            }

            if (isset($this->param['cellphone']) && $userInfo['cellphone'] != $this->param['cellphone']){
                // DONE 修改手机号  需要同步修改冗余信息
                $Member->where(['referCellphone' => $userInfo['cellphone']])->update(['referCellphone' => $this->param['cellphone']]);
                $Member->where(['cityCellphone' => $userInfo['cellphone']])->update(['cityCellphone' => $this->param['cellphone']]);
                $Member->where(['regionCellphone' => $userInfo['cellphone']])->update(['regionCellphone' => $this->param['cellphone']]);
                $Member->where(['shopCellphone' => $userInfo['cellphone']])->update(['shopCellphone' => $this->param['cellphone']]);
            }

            if ($record != []) {
                $this->model('MemberRecord')->insertAll($record);
            }
            $res = $this->model()->updateDataById($this->param, $this->param['Id']);


            $data = $this->userInfo($this->param);

            if($data){
                //查询会员的体检信息
                $tj = DB::table('admin_userinfo')->where('uid',$this->param['id'])->find();
                foreach ($data as $key => $value){
                    if($value !== $tj[$key]){
                         break;
                     }else{
                        unset($data[$key]);
                     }
                }
                if(!empty($data)){
                    $a = DB::table('admin_userinfo')->where('uid',$this->param['id'])->update($data);
                    $this->abort($a, ['msg' => '体检信息修改失败!']);
                }
            }
            $Member->commit();
        } catch (\Exception $e) {
            $Member->rollback();
            $this->error(['msg' => $e->getMessage()]);
        }
        $this->result($res, ['msg' => self::$model->getError()]);
    }

    /**
     * 现金账户和电子币账户互转
     *
     * @return void
     */
    public function PUTChange()
    {
        $this->abort(isset($this->param['type']), ['msg' => '转换类型不能为空!']);
        $this->abort(isset($this->param['change']), ['msg' => '转换金额不能为空!']);
        $Member = $this->model();
        $userInfo = $Member->get($this->param['userId']);
        $Member->startTrans();
        try {
            switch ($this->param['type']) {
                case 1:
                    // DONE 现金转到电子币
                    if ($userInfo['balance'] < $this->param['change']) {
                        throw new \Exception('账户余额不足!');
                    }
                    $record[] = [
                        'userId' => $this->param['userId'],
                        'username' => $userInfo['username'],
                        'change' => -$this->param['change'],
                        'remain' => $userInfo['balance'] - $this->param['change'],
                        'type' => 1,
                        'remark' => '现金转到电子币',
                    ];
                    $record[] = [
                        'userId' => $this->param['userId'],
                        'username' => $userInfo['username'],
                        'change' => $this->param['change'],
                        'remain' => $userInfo['emoney'] + $this->param['change'],
                        'type' => 3,
                        'remark' => '现金转到电子币',
                    ];
                    $Member->where(['id' => $this->param['userId']])->setDec('balance', $this->param['change']);
                    $Member->where(['id' => $this->param['userId']])->setInc('emoney', $this->param['change']);
                    break;
                case 2:
                    // DONE 电子币转到现金
                    if ($userInfo['emoney'] < $this->param['change']) {
                        throw new \Exception('电子币余额不足!');
                    }
                    $record[] = [
                        'userId' => $this->param['userId'],
                        'username' => $userInfo['username'],
                        'change' => $this->param['change'],
                        'remain' => $userInfo['balance'] + $this->param['change'],
                        'type' => 1,
                        'remark' => '电子币转到现金',
                    ];
                    $record[] = [
                        'userId' => $this->param['userId'],
                        'username' => $userInfo['username'],
                        'change' => -$this->param['change'],
                        'remain' => $userInfo['emoney'] - $this->param['change'],
                        'type' => 3,
                        'remark' => '电子币转到现金',
                    ];
                    $Member->where(['id' => $this->param['userId']])->setInc('balance', $this->param['change']);
                    $Member->where(['id' => $this->param['userId']])->setDec('emoney', $this->param['change']);
                    break;
            }

            $this->model('MemberRecord')->insertAll($record);
            $Member->commit();
        } catch (\Exception $e) {
            $Member->rollback();
            // $this->error(['msg' => '转换失败!']);
            $this->error(['msg' => $e->getMessage()]);
        }
        $this->result();
    }

    private function getReferInfo($referUsername, $model)
    {
        $res = $model->where(['username' => $referUsername])->where('roleId', 'neq', '2')->find(); // 店铺不能当推荐人
        $this->abort($res, ['msg' => '推荐人不存在']);
        $referInfo['referId'] = $res['id'];
        $referInfo['referCellphone'] = $res['cellphone'];
        return $referInfo;
    }

    /**
     * 获取所属区账户信息
     *
     * @param [type] $referUsername
     * @param [type] $model
     * @return void
     */
    private function getRegionInfo($regionId, $model)
    {
        $res = $model->where(['id' => $regionId])->where('roleId', 5)->find();
        $this->abort($res, ['msg' => '区账户不存在!']);
        $regionInfo['regionUsername'] = $res['username'];
        $regionInfo['regionCellphone'] = $res['cellphone'];
        return $regionInfo;
    }

    private function getProvinceInfo($provinceId, $model)
    {
        $res = $model->where(['id' => $provinceId])->where('roleId', 4)->find();
        $this->abort($res, ['msg' => '省账户不存在!']);
        $provinceInfo['provinceUsername'] = $res['username'];
        $provinceInfo['provinceCellphone'] = $res['cellphone'];
        return $provinceInfo;
    }

    /**
     * 获取所属市账户信息
     *
     * @param [type] $referUsername
     * @param [type] $model
     * @return void
     */
    private function getCityInfo($cityId, $model)
    {
        $res = $model->where(['id' => $cityId])->where('roleId', 3)->find();
        $this->abort($res, ['msg' => '市账户不存在!']);
        $cityInfo['cityUsername'] = $res['username'];
        $cityInfo['cityCellphone'] = $res['cellphone'];
        return $cityInfo;
    }

    /**
     * 获取所属店铺账户信息
     *
     * @param [type] $referUsername
     * @param [type] $model
     * @return void
     */
    private function getshopInfo($shopId, $model)
    {
        $res = $model->where(['id' => $shopId])->where('roleId', 2)->find();
        $this->abort($res, ['msg' => '店铺账户不存在!']);
        $shopInfo['shopUsername'] = $res['username'];
        $shopInfo['shopCellphone'] = $res['cellphone'];
        return $shopInfo;
    }

    /**
     * 读取并缓存系统配置
     */
    private function Configs()
    {
        $systemConfig = Cache::get('PUDU_CONFIG_DATA');
        if (!$systemConfig) {
            //获取所有系统配置
            $model = $this->model('PuduConfig');
            $systemConfig = $model->getDataOfList();
            // 检查是否抛出异常
            $this->abort($systemConfig, '应用配置获取失败');
            Cache::set('PUDU_CONFIG_DATA', null);
            Cache::set('PUDU_CONFIG_DATA', $systemConfig, 36000); //缓存配置
        }
        return $systemConfig;
    }

    public function GETForRealName()
    {
        // TODO 获取该用户名对应的真实姓名
        $realName = null;
        if (isset($this->param['username'])) {
            $realName = $this->model()->where(['username' => $this->param['username']])->where('roleId', 'neq', '2')->value('realName');
        }
        $this->json(['data' => $realName]);
    }

    /**
     * 批量禁用启用账户 账户被禁用 推荐关系直接移除
     *
     * @return void
     */
    public function POSTEnables()
    {
        $res = $this->model()->enableDatas($this->param['ids'], $this->param['status']);
        $this->result($res, ['msg' => self::$model->getError()]);
    }

    /**
     * 董事级别审核
     *
     * @return void
     */
    private function checkLevel($Member, $referId)
    {

    }

    /**
     * 推荐店铺数量 计数器
     *
     * @param [type] $referUserInfo 推荐人信息
     * @param [type] $number 推荐人数
     * @param [type] $Member 数据模型对象
     * @return void
     */
    private function referShopNumPlus($referUserInfo, $number, $Member)
    {
        $Member->where(['id' => $referUserInfo['id']])->setInc('referShopNum', $number);
        $this->updateLevel($number, $referUserInfo, $Member);
    }

    /**
     * 通过推荐人数来核准董事级别
     *
     * @param [type] $number 本地推荐数量
     * @param [type] $referUserInfo 推荐人信息
     * @param [type] $Member 模型对象
     * @return void
     */
    private function updateLevel($number, $referUserInfo, $Member)
    {
        $referShopNum = $referUserInfo['referShopNum'] + $number; // 更新之后的推荐店铺数量

        // TODO 更新董事级别
        $configs = $this->Configs();
        $limit1 = $configs['LEVEL_NUM_1'];
        $limit2 = $configs['LEVEL_NUM_2'];
        $limit3 = $configs['LEVEL_NUM_3'];
        $limit4 = $configs['LEVEL_NUM_4'];
        $limit5 = $configs['LEVEL_NUM_5'];
        $limit6 = $configs['LEVEL_NUM_6'];
        $limit7 = $configs['LEVEL_NUM_7'];

        if ($referShopNum >= $limit1 and $referShopNum < $limit2) { // 2-10 一级董事
            $updateData['level'] = 1;
        }

        if ($referShopNum >= $limit2 and $referShopNum < $limit3) { // 2-10 一级董事
            $updateData['level'] = 2;
        }

        if ($referShopNum >= $limit3 and $referShopNum < $limit4) { // 2-10 一级董事
            $updateData['level'] = 3;
        }

        if ($referShopNum >= $limit4 and $referShopNum < $limit5) { // 2-10 一级董事
            $updateData['level'] = 4;
        }

        if ($referShopNum >= $limit5 and $referShopNum < $limit6) { // 2-10 一级董事
            $updateData['level'] = 5;
        }

        if ($referShopNum >= $limit6 and $referShopNum < $limit7) { // 2-10 一级董事
            $updateData['level'] = 6;
        }

        if ($referShopNum >= $limit7) { // 2-10 一级董事
            $updateData['level'] = 7;
        }

        $res = $Member->where(['id' => $referUserInfo['id']])->update($updateData);
    }
    /**
        转让积分 现金  赠送医养储备金 可用医养储备金
    **/

    public function POSTGiveMoney()
    {
        $param = $this->param;
        if(!isset($param['fromId']) || !isset($param['username']) || !isset($param['giveMoney']) || !isset($param['type']))
        if($param['type'] == '4'){
            //积分转账
            $data['point'] = $param['point'];
            Db::startTrans();
            $a = DB::table('pudu_members')->where('id',$param['fromId'])->setDec('point',$param['giveMoney']);
            try{
                if (!$id){
                    throw new \Exception("转出账户异常");
                } 
                $b = DB::table('pudu_members')->where('username',$param['username'])->setInc('point',$param['giveMoney']);
                if (!$b) {
                    throw new \Exception("转入账户异常");
                }
                $findFrom = DB::table('pudu_members')->where('id',$param['fromId'])->find();
                $arr['userId'] = $param['fromId'];
                $arr['change'] = '-'.$param['giveMoney'];
                $arr['remain'] = $findFrom['point'];
                $arr['createDate'] = date('Y-m-d H:i:s');
                $arr['type'] = 2;
                $arr['type'] = $param['remark'];
                $c = DB::table('pudu_members_record')->insert($arr);
                if(!$c){
                    throw new \Exception("转出记录生成失败");
                }
                $findTo = DB::table('pudu_members')->where('username',$param['username'])->find();
                $array['userId'] = $findTo['id'];
                $array['change'] = $param['giveMoney'];
                $array['remain'] = $findTo['point'];
                $array['createDate'] = date('Y-m-d H:i:s');
                $array['type'] = 2;
                $array['type'] = $param['remark'];
                $d = DB::table('pudu_members_record')->insert($array);
                if(!$d){
                    throw new \Exception("转入记录生成失败");
                }
                // 执行提交操作
                Db::commit();
            }catch(\Exception $e){
                // 回滚事务
                Db::rollback();
                // 获取提示信息
                //$this->json(['code'=>'400','msg'=>$e->getMessage(),'data'=>false]);
                $this->result(false,$e->getMessage(),false);
            }

        }else{
            //其余转账暂不支持
             $this->error(['msg' => '未知操作,请检查']);
        }
        //$this->json(['code'=>'200','msg'=>'转账成功','data'=>true]);
        $this->result(true,'转账成功',true);
    }
    //存储会员体检信息
    public function userInfo($param)
    {
        if(isset($param['sex'])){
            $data['sex'] = $param['sex'];
        }
        if(isset($param['height'])){
            $data['height'] = $param['height'];
        }
        if(isset($param['weight'])){
            $data['weight'] = $param['weight'];
        }
        if(isset($param['waist'])){
            $data['waist'] = $param['waist'];
        }
        if(isset($param['birthday'])){
            $data['birthday'] = $param['birthday'];
        }
        if(isset($param['blood'])){
            $data['blood'] = $param['blood'];
        }
        if(isset($param['sugar'])){
            $data['sugar'] = $param['sugar'];
        }
        if(isset($param['depart'])){
            $data['depart'] = $param['depart'];
        }
        if(isset($param['company'])){
            $data['company'] = $param['company'];
        }
        if(isset($param['address'])){
            $data['address'] = $param['address'];
        }
        if(isset($param['reson'])){
            $data['reson'] = $param['reson'];
        }
        return $data;
    }
    //查询体检信息 会员个人查看
    public function POSTuserIndex()
    {
        $id = $this->param['userId'];
        //查询此用户的体检细信息
        $data = DB::table('admin_userinfo')->where('uid',$id)->find();
        $this->json(['data' =>$data]);
    }
    //查询表体检信息  店铺查看
    public function GETuserIndex()
    {
        $id = $this->param['Id'];
        if(!$id){
            $this->json(['data'=>'参数错误']);
        }
        $data = DB::table('pudu_members')->where('id',$id)->find();
        $find = DB::table('admin_userinfo')->where('uid',$id)->find();
        if($find){
           $data = array_merge($data,$find);
        }
        $this->json(['data'=>$data]);
    }
    //店铺编辑会员信息
    public function POSTuserEdit()
    {
        $param = $this->param;
        //提取会员体检信息
        $data = $this->userInfo($param);

        //提取需要在用户表里修改的字段
        $user_data['username'] = $param['username'];
        $user_data['realName'] = $param['realName'];
        $user_data['cellphone'] = $param['cellphone'];
        //推荐人账户不可修改  暂不获取  支付修改单独 计算
        //查询用户信息
        $users = DB::table('pudu_members')->where('id',$param['uid'])->find();
        //遍历比对
        foreach ($user_data as $key => $value) {
            if($value !== $users[$key]){
                 break;
             }else{
                unset($user_data[$key]);
             }
        }
        //在获取是否有修改密码的操作
        $password = $param['paypassForModify'];
        if($password){
            $user_data['paypass'] = user_md5($password);
        }
        //$user_data = array_diff($param,$data);
        $find1 = DB::table('admin_userinfo')->where('uid',$param['uid'])->find();
        //遍历比对  是否修改过
        foreach($data as $k => $v){
            if($v !== $find1[$k]){
                break;
            }else{
                unset($data[$k]);
            }
        }
        //进行判断  数据库操作 会员信息进行修改  体检信息不修改
        try{
            if($user_data && !$data){
                $res = DB::table('pudu_members')->where('id',$param['uid'])->update($user_data);
                if(!$res){
                    throw new \Exception('会员信息修改失败!');
                }
            }elseif(!$user_data && $data){
                $res = DB::table('admin_userinfo')->where('uid',$param['uid'])->update($data);
                if(!$res){
                    throw new \Exception('会员体检信息修改失败!');
                }
            }elseif($user_data && $data){
                Db::startTrans();
                $a = DB::table('pudu_members')->where('id',$param['uid'])->update($user_data);
                if(!$a){
                    throw new \Exception('会员信息修改失败!');
                }
                $b = DB::table('admin_userinfo')->where('uid',$param['uid'])->update($data);
                if(!$b){
                    throw new \Exception('会员体检信息修改失败!');
                }
                Db::commit();
            }else{
                throw new \Exception('没有修改操作!');
            }   
        }catch (\Exception $e){
             Db::rollback();
            $this->error(['msg' => $e->getMessage()]);
        }

        $this->json(['data'=>'修改成功']);
    }
    //总后台获取 会员的体检信息
    public function POSTadminIndex()
    {
        $param = $this->param;
        $data = DB::table('admin_userinfo')->where('uid',$param['id'])->find();
        if($data){
            $param['sex'] = $data['sex'];
            $param['height'] = $data['height'];
            $param['weight'] = $data['weight'];
            $param['waist'] = $data['waist'];
            $param['birthday'] = $data['birthday'];
            $param['blood'] = $data['blood'];
            $param['sugar'] = $data['sugar'];
            $param['depart'] = $data['depart'];
            $param['company'] = $data['company'];
            $param['address'] = $data['address'];
            $param['reson'] = $data['reson'];
        }
        $this->json(['data'=>$param]);
    }

    //总后台修改会员信息
    public function POSTadminUser()
    {
        $param = $this->param;
        $id = $param['id'];
        //先查看是否有体检信息的修改记录
        $tj = $this->userInfo($param);
        $find_tj = DB::table('admin_userinfo')->where('uid',$id)->find(); 
        foreach ($tj as $key => $value) {
            if($value !== $find_tj[$key]){
                 break;
             }else{
                unset($tj[$key]);
             }
        }
        //查询原始会员信息进行比对
        $find_user = DB::table('pudu_members')->where('id',$id)->find();



        //获取传过来的值
        $user['cellphone'] = $param['cellphone'];//手机号码
        $user['bankNumber'] = $param['bankNumber'];//银行卡号
        $user['bankAddress'] = $param['bankAddress'];//开户行
        $user['bankName'] = $param['bankName'];//银行名称
        $user['cardholder'] = $param['cardholder'];//持卡人
        $user['referShopNum'] = $param['referShopNum'];//推荐数量
        $user['level'] = $param['level'];//董事级别
        $user['province'] = $param['province'];//
        $user['city'] = $param['city'];//所属省
        //获取手否有修改支付密码的操作 
        if(isset($param['paypassForModify']) && user_md5($param['paypassForModify']) !== $find_user['paypass']){
            $user['paypass'] = user_md5($param['paypassForModify']);
        }
        //查询推荐人是否做过修改
        if(isset($param['referUsername']) && $param['referUsername'] !== $find_user['referUsername']){
            //查询此推荐人是否存在
            $find_tjr = DB::table('pudu_members')->where('username',$param['referUsername'])->find();
            $this->abort($find_tjr, ['msg' => '此推荐人不存在!']);
            $user['referUsername'] = $param['referUsername'];
            $user['referCellphone'] = $find_tjr['cellphone'];
            $user['referId'] = $find_tjr['referId'];
        }
        //插损所属店铺是否修改
        if(isset($param['shopUsername']) && $param['shopUsername'] !== $find_user['shopUsername']){
            //查询此推荐人是否存在
            $find_shop = DB::table('pudu_members')->where('username',$param['shopUsername'])->find();
            $this->abort($find_shop, ['msg' => '修改的所属店铺不存在!']);
            $user['shopUsername'] = $param['shopUsername'];
            $user['shopId'] = $find_shop['id'];
            $user['shopCellphone'] = $find_shop['shopCellphone'];
        }

        try{
            Db::startTrans();
            //查询是否有现金 积分账户的变化
            if(isset($param['balance']) && $param['balance'] !== $find_user['balance']){
                if(!isset($param['remark'])){
                    throw new \Exception('请输入本次修改的备注信息!');
                }
                //查询此推荐人是否存在
               $user['balance'] = $param['balance'];
               //生成现金账户的记录
               $balance['userId'] = $id;
               $balance['username'] = $find_user['username'];
               $balance['change'] = $param['balance'] - $find_user['balance'];
               $balance['remain'] = $param['balance'];
               $balance['createDate'] = date('Y-m-d H:i:s');
               $balance['type'] = 1; //现金账户
               $balance['remark'] = $param['remark'];
               //存储数据库
               $a = DB::table('pudu_members_record')->insert($balance);
               if(!$a){
                    throw new \Exception('现金账户存储失败!');
               }
            }

            if(isset($param['point']) && $param['point'] !== $find_user['point']){
                if(!isset($param['remark'])){
                    throw new \Exception('请输入本次修改的备注信息!');
                }
                //查询此推荐人是否存在
               $user['point'] = $param['point'];
               //生成现金账户的记录
               $point['userId'] = $id;
               $point['username'] = $find_user['username'];
               $point['change'] = $param['point'] - $find_user['point'];
               $point['remain'] = $param['point'];
               $point['createDate'] = date('Y-m-d H:i:s');
               $point['type'] = 2; //现金账户
               $point['remark'] = $param['remark'];
               //存储数据库
               $b = DB::table('pudu_members_record')->insert($point);
               if(!$b){
                    throw new \Exception('积分账户存储失败!');
               }
            }

            //查询登录账户信息
            $find_admin = DB::table('admin_user')->where('userId',$id)->find();
            //登录密码
            if(isset($param['password']) && user_md5($param['password']) !== $find_admin['password']){
                $admin['password'] = user_md5($param['password']);
                $res = DB::table('admin_user')->where('userId',$id)->update($admin);
                if(!$res){
                    throw new \Exception('登录密码修改失败!');
                }
            }


            //查询洗肠记录
            $find_xc = DB::table('pudu_wash_record')->where('userId',$id)->order('createDate desc')->find();
            if($find_xc){
                if(isset($param['washTimes']) && $param['washTimes'] !== $find_xc['washTimes']){
                    $xc['washTimes'] = intval($param['washTimes']);
                    $xc['userId'] = $id;
                    $xc['createDate'] = date('Y-m-d H:i:s');//remark
                    $xc['remark'] = '后台修改';
                    //生成洗肠记录
                    $c = DB::table('pudu_wash_record')->insert($xc);
                    if(!$c){
                        throw new \Exception('洗肠记录存储失败!');
                    }
                }
            }else{
                if(isset($param['washTimes'])){
                    $xc['washTimes'] = intval($param['washTimes']);
                    $xc['userId'] = $id;
                    $xc['createDate'] = date('Y-m-d H:i:s');//remark
                    $xc['remark'] = '后台修改';
                    $c = DB::table('pudu_wash_record')->insert($xc);
                    if(!$c){
                        throw new \Exception('洗肠记录存储失败!');
                    }
                }
            }
            
            
            //修改体检信息
            if($tj){
                //查看是否有体检信息
                $find_tj = DB::table('admin_userinfo')->where('uid',$id)->find();
                if(!$find_tj){
                    $tj['uid'] =$id;
                    $d = DB::table('admin_userinfo')->insert($tj);
                }else{
                    $d = DB::table('admin_userinfo')->where('uid',$id)->update($tj);
                }
                if(!$d){
                    throw new \Exception('体检信息修改失败!');
                }
            }
            //修改会员的基础信息
            foreach($user as $k => $v){
                if($v !== $find_user[$k]){
                    break;
                }else{
                    unset($user[$k]);
                }
            }
            if($user){
                $h = DB::table('pudu_members')->where('id',$id)->update($user);
                if(!$h){
                    throw new \Exception('会员基础信息修改失败!');
                }
            }
            Db::commit();
        }catch (\Exception $e){
             Db::rollback();
            $this->error(['msg' => $e->getMessage()]);
        }


        $this->json(['data'=>'修改成功']);
    }
}
